package net.kqinfo.core.controller;

import net.kqinfo.common.util.scrypt.BCrypt;
import net.kqinfo.core.Constants;
import net.kqinfo.core.model.Module;
import net.kqinfo.core.model.User;

import org.apache.shiro.authz.annotation.RequiresAuthentication;

import com.jfinal.core.Controller;
import com.jfinal.ext.render.CaptchaRender;
import com.jfinal.ext.render.DwzRender;

public class IndexController extends Controller {
	
	private static final String INDEX = "/WEB-INF/views/management/index/index.html";
	private static final String UPDATE_PASSWORD = "/WEB-INF/views/management/index/updatePwd.html";
	private static final String UPDATE_BASE = "/WEB-INF/views/management/index/updateBase.html";
	
	@RequiresAuthentication
	public void index() {
		Module menuModule = Module.dao.findFirst("select * from security_module where id = 1");
		setAttr("modules",menuModule.getChildren());
		render(INDEX);
	}
	

//	public void login() {
//		renderFreeMarker(LOGINPAGE);
//	}

	public void captcha(){
		render(new CaptchaRender(Constants.RANDOM_CODE_KEY));
	}
	
//	public void doLogin(){
//		System.out.println("in dologin");
//		System.out.println(SecurityUtils.getSecurityManager());
//		String inputRandomCode = getPara("inputRandomCode");
//		String username = getPara("username");
//		String password = getPara("password");
//		boolean loginSuccess = CaptchaRender.validate(this, inputRandomCode.toUpperCase(), RANDOM_CODE_KEY);
//		if (loginSuccess) {
//			User user = User.dao.findFirst("select * from security_user where username = ? ",username);
//			if (user==null) {
//				render(DwzRender.error());
//			}else{
//				if (BCrypt.checkpw(password, user.getStr("password"))) {
//					setSessionAttr(Constants.LOGIN_USER, user);
//					redirect("/");
//				}else{
//					render(DwzRender.error());
//				}
//			}
//		} else {
//			redirect("/login");
//		}
//	}
	
	public void updateBase(){
		render(UPDATE_BASE);
	}
	
	public void update(){
		User user = getSessionAttr(Constants.LOGIN_USER);
		user.set("phone", getPara("phone"));
		user.set("email", getPara("email"));
		user.update();
		setSessionAttr(Constants.LOGIN_USER, user);
		render(DwzRender.closeCurrentAndRefresh("main"));
	}
	
	public void updatePwd(){
		render(UPDATE_PASSWORD);
	}
	
	public void updatePassword(){
		User user = getSessionAttr(Constants.LOGIN_USER);
		String plainPassword = getPara("plainPassword");
		String rPassword = getPara("rPassword");
		if (plainPassword.equals(rPassword)) {
			user.set("password", BCrypt.hashpw(plainPassword, BCrypt.gensalt(Constants.BCRYPT_LOG_ROUNDS)));
			user.update();
			render(DwzRender.closeCurrentAndRefresh("main"));
		}else {
			render(DwzRender.error());
		}
	}
}
